namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
    /// <summary>
    /// 1. Start at Workplace homepage
    /// 2. Select Activities
    /// 3. Select Task from "Type" drop down list.
    /// 4. Select "All Tasks" from "View" drop down list
    /// 5. Enter a random string of two characters and click "Find"
    /// 6. Double Click on a task
    /// 7. Change description
    /// 8. Save and close
    /// </summary>
    
    public class UpdateTask : CrmWebTest
    {
        public void UpdateTask_PreWebTest(object sender, PreWebTestEventArgs e)
        {
			EntityRequest er = new EntityRequest();
			er.Type = EntityNames.Users;
			er.ReturnAs = EntityNames.Users;
			er.ParentID = EntityManager.Instance.OrgId;

			System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }
            
			EntityRequest TaskEr = new EntityRequest();
			TaskEr.Type = EntityNames.Tasks;
			TaskEr.ParentID = Guid.NewGuid();
			TaskEr.ReturnAs = EntityNames.Tasks;

			Props.Add(EntityNames.Tasks, new EntityRequest[] { TaskEr });

			er.Props = Props;

			System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

			user = (CRMEntity)Entities[EntityNames.Users];
			task = (CRMEntity)Entities[EntityNames.Tasks];
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
        }

        public void UpdateTask_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            // Don't delete the entity till end of test run as it is deleted from crm.
            EntityManager.Instance.FreeEntity(user);
            EntityManager.Instance.FreeEntity(task);
        }

        public UpdateTask()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            string random = Utils.GetRandomString(2, 2);
            gridXml1 = GridXmlHelper.TaskPageView(-1, myTasksViewId, null, null, null);
            gridXml2 = GridXmlHelper.TaskPageView(-1, allTasksViewId, null, "4212", "1&#x2C;1");
            gridXml3 = GridXmlHelper.TaskSearchView(-1, searchTaskViewId, random, null, "4212", "1&#x2C;1&#x2C;1");
            gridXml4 = GridXmlHelper.TaskPageSearchViewRefresh(-1, searchTaskViewId, random, null);
            
            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(UpdateTask_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(UpdateTask_PostWebTest);
        }
        
        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
			this.BeginTransaction("NavActivityHomepage");

            // Get the home page
            workplace_home_activities_aspx hp = new workplace_home_activities_aspx(user);
            yield return (hp);

			this.EndTransaction("NavActivityHomepage");

            this.BeginTransaction("NavMyTasks");
            
			// Choose task from activities drop down menu
            ActivitiesWebService.ActivitiesWebService act = new ActivitiesWebService.ActivitiesWebService();
            WebTestRequest wtr = null;

            try { act.GetQueryList(entityName); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            AppGridWebService.AppGridWebService ag = new AppGridWebService.AppGridWebService();
            wtr = null;

            try { ag.Reset(gridXml1, gridId); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("NavMyTasks");

            if (ConfigSettings.Default.alltasks == true)
            {
                this.BeginTransaction("NavAllTasks");

                // Search for all tasks
                ag = new AppGridWebService.AppGridWebService();
                wtr = null;

                try { ag.Reset(gridXml2, gridId); }
                catch (crmException x)
                {
                    wtr = (CrmRequest)x.wtr;
                    wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                    string urlPath = wtr.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtr.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtr.Headers.Add(headerItem);
                    wtr.Method = "Post";
                }
                yield return (wtr);

                this.EndTransaction("NavAllTasks");
            }
             
            this.BeginTransaction("SearchTasks");

            ag = new AppGridWebService.AppGridWebService();
            wtr = null;

            try { ag.Reset(gridXml3, gridId); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("SearchTasks");
            
            this.BeginTransaction("OpenTask");

            // simulate double clicking of a task
            activities_task_edit_aspx dp = new activities_task_edit_aspx(user);
            dp.id = task["activityid"];
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx f = new _forms_FormScript_js_aspx(user);
            f.etc = 4212;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);

            this.EndTransaction("OpenTask");
            
            this.BeginTransaction("UpdateTask");

            _controls_number_formatNumber_xsl format = new _controls_number_formatNumber_xsl(crmServer);
            yield return (format);

            activities_task_edit_aspx updateFormPage = new activities_task_edit_aspx(user);            
            // QueryString Parameters
            updateFormPage.id = task["activityid"];
            // Form Parameters
            updateFormPage.crmFormSubmitXml = EntityXmlHelper.GetUpdateTaskXml();

            rpcInfo = Utils.GenerateWRPCToken(activities_task_edit_aspx.url, user, tokenKey);
            updateFormPage.CRMWRPCToken = rpcInfo.token;
            updateFormPage.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            updateFormPage.crmFormSubmitMode = 2;
            updateFormPage.crmFormSubmitId = new Guid(task["activityid"]);
            updateFormPage.crmFormUserModified = true;
            updateFormPage.crmFormSubmitObjectType = 4212;
            updateFormPage.crmFormSubmitSecurity = 852023;
            updateFormPage.crmFormSubmitOnline = 1;
            yield return (updateFormPage);

            ag = new AppGridWebService.AppGridWebService();
            wtr = null;

            try { ag.Refresh(gridXml4); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("UpdateTask");
        }

        private string gridXml1;
        private string gridXml2;
        private string gridXml3;
        private string gridXml4;
        private static string gridId = "crmGrid";
        private static string entityName = "task";
        private CRMEntity user;
        private CRMEntity task;
        private string crmServer;
        private string tokenKey;
        private static string myTasksViewId = "6CF285AA-EB20-4277-925A-3E9735411FF0";
        private static string allTasksViewId = "2B5F5A5D-2D23-4FE7-AA58-E77995368AE7";
        private static string searchTaskViewId = "B2397CA2-8672-4863-BC69-B65802061665";

        private Guid orgId;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
        private string referer;
    }
}